import numpy as np
import matplotlib.pyplot as plt
import numpy.random as npr
import matplotlib
matplotlib.use(backend="TkAgg")

def experiment():
    n,p = 10, 0.3
    trials = 100_000

    # 模拟数据
    '''
    Draw samples from a binomial distribution.
        
    Samples are drawn from a binomial distribution with specified
    parameters, n trials and p probability of success where
    n an integer >= 0 and p is in the interval [0,1]. (n may be
    input as a float, but it is truncated to an integer in use)
    '''
    samples_binom = npr.binomial(n=n, p=p, size=trials)

    theoric_mean = n * p

    empirical_mean = sum(samples_binom) / trials

    # 画图
    plt.figure(figsize=(6,4))
    plt.hist(samples_binom, bins=range(n+2), density=True, alpha=0.6, color='skyblue', edgecolor='black')
    plt.axvline(theoric_mean, color='red', linestyle='--', label=f'Theoretical E[X]={theoric_mean:.2f}')
    plt.axvline(empirical_mean, color='green', linestyle=':', label=f'Empirical mean={empirical_mean:.2f}')
    plt.title(f'Binomial Distribution (n={n}, p={p})')
    plt.xlabel("X")
    plt.ylabel("Frequency")
    plt.legend()
    plt.show()

# result of flipping a coin 10 times, tested 1000 times.
def test01():
    n,p=10,.5
    trials=100
    samples_binom = npr.binomial(n=n, p=p, size=trials)
    print(samples_binom)

'''
 A real world example. A company drills 9 wild-cat oil exploration
wells, each with an estimated probability of success of 0.1. All nine
wells fail. What is the probability of that happening?
    
Let's do 20,000 trials of the model, and count the number that
generate zero positive results.
'''
def test02():
    ans = sum(npr.binomial(n=9,p=0.1,size=20_000)==0)/20_000
    print(ans)


if __name__ == '__main__':
    # test01()
    test02()